package com.my.lucky.service;

import com.my.lucky.model.Gainian60Boll;
import com.my.lucky.model.Stock60Boll;
import com.my.lucky.repository.Gainian60BollRepository;
import com.my.lucky.repository.Stock60BollRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

@Service
public class Gainian60BollService {

    private static final Logger log = LoggerFactory.getLogger(Gainian60BollService.class);

    @Autowired
    private Gainian60BollRepository gainian60BollRepository;

    /**
     * 保存或更新股票60分钟线Bollinger Bands数据
     * 当记录存在时，只更新非null字段
     */
    @Transactional
    public Gainian60Boll saveOrUpdate(Gainian60Boll gainian60Boll) {
        if (gainian60Boll == null) {
            throw new IllegalArgumentException("gainian60Boll cannot be null");
        }

        try {
            return gainian60BollRepository.saveOrUpdate(gainian60Boll);
        } catch (Exception e) {
            log.error("Failed to save or update Stock60Boll: {}", gainian60Boll, e);
            throw new ServiceException("保存或更新股票60分钟线Bollinger Bands数据失败", e);
        }
    }

    /**
     * 批量保存或更新
     */
    @Transactional
    public List<Gainian60Boll> saveOrUpdateAll(List<Gainian60Boll> gainian60Boll) {
        if (gainian60Boll == null || gainian60Boll.isEmpty()) {
            return gainian60Boll;
        }

        try {
            return (List<Gainian60Boll>) gainian60BollRepository.saveOrUpdateAll(gainian60Boll);
        } catch (Exception e) {
            log.error("Failed to batch save or update Stock60Boll", e);
            throw new ServiceException("批量保存或更新股票60分钟线Bollinger Bands数据失败", e);
        }
    }

    /**
     * 根据股票代码和交易日期查询
     */
    public Optional<Gainian60Boll> findByCodeAndTradeDate(String code, LocalDate tradeDate) {
        if (code == null || code.trim().isEmpty() || tradeDate == null) {
            return Optional.empty();
        }
        return gainian60BollRepository.findByCodeAndTradeDate(code, tradeDate);
    }

    /**
     * 自定义业务异常
     */
    public static class ServiceException extends RuntimeException {
        public ServiceException(String message, Throwable cause) {
            super(message, cause);
        }
    }
}